<?php

/**
 * ECSHOP 管理中心品牌管理
 * ============================================================================
 * 版权所有 2005-2009 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: brand.php 16881 2009-12-14 09:19:16Z liubo $
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
include_once(ROOT_PATH . 'includes/lib_taoapi.php');

$exc = new exchange($ecs->table("shop"), $db, 'sid', 'shop_title');

if($_REQUEST['act'] == 'insert' or $_REQUEST['act'] == 'updata'){
	$nick = $_POST['nick'];
    
	/*获取用户信息*/
	$TaoUser = taobao_user_get($nick);
	$user_id = $TaoUser['user_id'];
	$last_visit = $TaoUser['last_visit'];
	$location = $TaoUser['location']['address'];
	$level = $TaoUser['seller_credit']['level'];
	$total_num = $TaoUser['seller_credit']['total_num'];
	$good_num = $TaoUser['seller_credit']['good_num'];
	
    /*获取店铺数据*/
    $TaoShop = taobao_shop_get($nick);
    extract($TaoShop);
	
	/*店铺推广链接*/
	$TaoShops = taobao_taobaoke_shops_convert($sid);
	$click_url = $TaoShops['click_url'];
	$user_id = $TaoShops['user_id'];
	$commission_rate = $TaoShops['commission_rate'];
	$shop_title = $TaoShops['shop_title'];
}

/*------------------------------------------------------ */
//-- 品牌列表
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'list')
{
	$cat_id = empty($_REQUEST['cat_id']) ? 0 : intval($_REQUEST['cat_id']);
	
    $smarty->assign('ur_here',      $_LANG['07_shop_list']);
    $smarty->assign('action_link',  array('text' => $_LANG['07_shop_add'], 'href' => 'shop.php?act=add'));
    $smarty->assign('full_page',    1);

    $shop_list = get_shoplist();

    
    $smarty->assign('cat_list',     cat_shop_list(0, $cat_id));
    $smarty->assign('shop_list',   $shop_list['shop']);
    $smarty->assign('filter',       $shop_list['filter']);
    $smarty->assign('record_count', $shop_list['record_count']);
    $smarty->assign('page_count',   $shop_list['page_count']);

    /* 排序标记 */
    $sort_flag  = sort_flag($shop_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);
    
    assign_query_info();
    $smarty->display('shop_list.htm');
}

/*------------------------------------------------------ */
//-- 添加品牌
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'add')
{
    /* 权限判断 */
    admin_priv('shop_manage');

    $smarty->assign('ur_here',     $_LANG['07_shop_add']);
    $smarty->assign('action_link', array('text' => $_LANG['07_shop_list'], 'href' => 'shop.php?act=list'));
    $smarty->assign('form_action', 'insert');

    assign_query_info();
    $smarty->assign('shop', array('sort_order'=>50, 'is_show'=>1));
    $smarty->display('shop_info.htm');
}
elseif ($_REQUEST['act'] == 'insert')
{
    /*检查品牌名是否重复*/
    admin_priv('shop_manage');

    $is_show = isset($_REQUEST['is_show']) ? intval($_REQUEST['is_show']) : 0;

    $is_only = $exc->is_only('nick', $_POST['nick']);

    if (!$is_only)
    {
        sys_msg(sprintf($_LANG['nick_exist'], stripslashes($_POST['nick'])), 1);
    }
  
    /*插入数据*/
    $sql = "INSERT INTO ".$ecs->table('shop')."(sid, cat_id, user_id, nick, shop_title, level, total_num, good_num, click_url, 
    		commission_rate, title, `desc`, bulletin, pic_path, created, last_visit, modified, is_show, sort_order) ".
           "VALUES ('$sid', '$cid', '$user_id', '$nick', '$shop_title', '$level', '$total_num', '$good_num', '$click_url',
           	'$commission_rate', '$title', '$desc', '$bulletin', '$pic_path', '$created', '$last_visit', '$modified', '$is_show', '$_POST[sort_order]')";
    $db->query($sql);

    admin_log($_POST['nick'],'add','shop');

    /* 清除缓存 */
    clear_cache_files();

    $link[0]['text'] = $_LANG['continue_add'];
    $link[0]['href'] = 'shop.php?act=add';

    $link[1]['text'] = $_LANG['back_list'];
    $link[1]['href'] = 'shop.php?act=list';

    sys_msg($_LANG['shopadd_succed'], 0, $link);
}

/*------------------------------------------------------ */
//-- 编辑品牌
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit')
{
    /* 权限判断 */
    admin_priv('shop_manage');
    $sql = "SELECT * FROM " .$ecs->table('shop'). " WHERE sid='$_REQUEST[id]'";
    $shop = $db->GetRow($sql);

    $smarty->assign('ur_here',     $_LANG['shop_edit']);
    $smarty->assign('action_link', array('text' => $_LANG['07_shop_list'], 'href' => 'shop.php?act=list&' . list_link_postfix()));
    $smarty->assign('shop',       $shop);
    $smarty->assign('form_action', 'updata');

    assign_query_info();
    $smarty->display('shop_info.htm');
}
elseif ($_REQUEST['act'] == 'updata')
{
    admin_priv('shop_manage');
    if ($_POST['nick'] != $_POST['old_nick'])
    {
        /*检查品牌名是否相同*/
        $is_only = $exc->is_only('nick', $_POST['nick'], $_POST['id']);

        if (!$is_only)
        {
            sys_msg(sprintf($_LANG['nick_exist'], stripslashes($_POST['nick'])), 1);
        }
    }

    $sort_order = isset($_REQUEST['sort_order']) ? intval($_REQUEST['sort_order']) : 0;
    $is_show = isset($_REQUEST['is_show']) ? intval($_REQUEST['is_show']) : 0;
	$param = "cat_id='$cid', sid= '$sid', nick='$nick', user_id='$user_id', shop_title='$shop_title', level='$level', total_num='$total_num', good_num='$good_num', click_url='$click_url', commission_rate='$commission_rate', title='$title', `desc`='$desc', bulletin='$bulletin', pic_path='$pic_path', created='$created', last_visit='$last_visit', modified='$modified', is_show='$is_show', sort_order='$sort_order' ";
	
    if ($exc->edit($param,  $_POST['id']))
    {
        /* 清除缓存 */
        clear_cache_files();

        admin_log($_POST['shop_title'], 'edit', 'shop');

        $link[0]['text'] = $_LANG['back_list'];
        $link[0]['href'] = 'shop.php?act=list&' . list_link_postfix();
        $note = @vsprintf($_LANG['shopedit_succed'], $_POST['nick']);
        sys_msg($note, 0, $link);
    }
    else
    {
        die($db->error());
    }
}

/*------------------------------------------------------ */
//-- 编辑排序序号
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_sort_order')
{
    check_authz_json('brand_manage');

    $id     = intval($_POST['id']);
    $order  = intval($_POST['val']);
    $name   = $exc->get_name($id);

    if ($exc->edit("sort_order = '$order'", $id))
    {
        admin_log(addslashes($name),'edit','shop');

        make_json_result($order);
    }
    else
    {
        make_json_error(sprintf($_LANG['shopedit_fail'], $name));
    }
}

/*------------------------------------------------------ */
//-- 切换是否显示
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_show')
{
    check_authz_json('shop_manage');

    $id     = intval($_POST['id']);
    $val    = intval($_POST['val']);

    $exc->edit("is_show='$val'", $id);

    make_json_result($val);
}

/*------------------------------------------------------ */
//-- 切换是否显示
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_is_recommend')
{
    check_authz_json('shop_manage');

    $id     = intval($_POST['id']);
    $val    = intval($_POST['val']);

    $exc->edit("is_recommend='$val'", $id);

    make_json_result($val);
}

/*------------------------------------------------------ */
//-- 删除品牌
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'remove')
{
    check_authz_json('shop_manage');

    $id = intval($_GET['id']);

    /* 删除该店铺的商品 */
    $sql = "SELECT nick FROM " .$ecs->table('shop'). " WHERE sid = '$id'";
    $nick = $db->getOne($sql);
    if (!empty($nick))
    {
    	$query = $db->query("SELECT iid FROM ".$ecs->table('item'). " WHERE nick = '$nick'");
    	while ($item = $db->fetch_array($query)) {
    		$iid = $item['iid'];
    		$db->query("DELETE FROM " .$ecs->table('goods'). " WHERE goods_sn = '$iid'"); //删除本地商品
    		$db->query("DELETE FROM " .$ecs->table('item'). " WHERE iid = '$iid'"); //删除淘宝商品
    		$db->query("DELETE FROM " .$ecs->table('itemimg'). " WHERE iid = '$iid'");  //删除淘宝商品图片
    	}
    }

    $exc->drop($id);

    $url = 'shop.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

    ecs_header("Location: $url\n");
    exit;
}

/*------------------------------------------------------ */
//-- 排序、分页、查询
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'query')
{
    $shop_list = get_shoplist();
    $smarty->assign('shop_list',   $shop_list['shop']);
    $smarty->assign('filter',       $shop_list['filter']);
    $smarty->assign('record_count', $shop_list['record_count']);
    $smarty->assign('page_count',   $shop_list['page_count']);

    /* 排序标记 */
    $sort_flag  = sort_flag($shop_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);
    
    make_json_result($smarty->fetch('shop_list.htm'), '',
        array('filter' => $shop_list['filter'], 'page_count' => $shop_list['page_count']));
}

/**
 * 获取品牌列表
 *
 * @access  public
 * @return  array
 */
function get_shoplist()
{
    $result = get_filter();
    if ($result === false)
    {
        /* 分页大小 */
        $filter = array();

        $filter['cat_id']           = empty($_REQUEST['cat_id']) ? 0 : intval($_REQUEST['cat_id']);
        $filter['sort_by']          = empty($_REQUEST['sort_by']) ? 'level' : trim($_REQUEST['sort_by']);
        $filter['sort_order']       = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        $filter['shop_title']       = empty($_REQUEST['shop_title']) ? '' : trim($_REQUEST['shop_title']);
        $filter['nick']          	= empty($_REQUEST['nick']) ? '' : trim($_REQUEST['nick']);
        
        $where = $filter['cat_id'] > 0 ? " AND cat_id = '" . $filter['cat_id'] ."'" : "";
        
        /* 店铺名称 */
        if (!empty($filter['shop_title']))
        {
            $where .= " AND shop_title LIKE '%" . mysql_like_quote($filter['shop_title']) . "%'";
        }
        
        /* 淘宝昵称 */
        if (!empty($filter['nick']))
        {
            $where .= " AND nick LIKE '%" . mysql_like_quote($filter['nick']) . "%'";
        }
        
        /* 记录总数以及页数 */
        $sql = "SELECT COUNT(*) FROM ".$GLOBALS['ecs']->table('shop')." WHERE 1 $where";
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
        

        $filter = page_and_size($filter);

        
        $sql = "SELECT * FROM ".$GLOBALS['ecs']->table('shop')." WHERE 1 $where ".
        	" ORDER BY `".$filter['sort_by']."` ".$filter['sort_order'];
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $arr = array();
    while ($rows = $GLOBALS['db']->fetchRow($res))
    {
        $pic_path = empty($rows['pic_path']) ? '' :
            '<a href="http://logo.taobao.com/shop-logo/'.$rows['pic_path'].'" target="_brank"><img src="images/picflag.gif" width="16" height="16" border="0" alt='.$GLOBALS['_LANG']['pic_path'].' /></a>';
		$level_img = '<img src="../images/level_'.$rows['level'].'.gif" title="'.$rows['level'].'" alt="'.$rows['level'].'" />';
        $last_update = date("Y-m-d H:i:s", $rows['last_update']);
        $item_num = $GLOBALS['db']->getOne("SELECT COUNT(num_iid) FROM ".$GLOBALS['ecs']->table('item')." WHERE nick='$rows[nick]'");
        
        $rows['item_num'] = $item_num;
        $rows['last_update'] = $last_update;
        $rows['pic_path'] = $pic_path;
        $rows['level_img'] = $level_img;

        $arr[] = $rows;
    }

    return array('shop' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}

?>
